package knowse.app;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class FetchData {
	
	//Reads from the stream and return a string whit the data in the stream
	//Author Richard
	private String fetchFromURL(String url) throws IOException 
	{
		InputStream urlInput = new URL(url).openStream();
		try {
			InputStreamReader inputReader = new InputStreamReader(urlInput);
			BufferedReader reader = new BufferedReader(inputReader);
			StringBuilder string = new StringBuilder();
			int numRead;
			
			while((numRead = reader.read()) != -1)
			{
				string.append((char) numRead);
			}
			
			return string.toString();
		} catch (IOException e) {
			throw e;
		} finally {
			urlInput.close();
		}
		
		
	}
	
	//This was just to test dumping the string
	//Author Richard
	public String fetchData(String url) throws IOException
	{
		return fetchFromURL(url);
	}
	
	//Fetch data from a CSV-file located at URL and return the data as a string
	//Author Sebastian
	public Object fetchCSV(String URL) throws IOException
	{
		return fetchFromURL(URL);
	}
	
	//Creates a JSONArray from a fetched string
	//Author Richard
	public JSONArray fetchJSON(String URL) throws IOException
	{
		String jsonText = fetchFromURL(URL);
		
		try {
			return new JSONArray(jsonText); 
		} catch (JSONException e) {
			throw new IOException(e.toString());
		}
	}

	//Creates a JSONObject from a fetched string
	//Author Xi

	public JSONObject fetchJSON2Object(String URL) throws IOException
	{
		String jsonText = fetchFromURL(URL);
		
		try {
			JSONObject jobj =new JSONObject(jsonText);
			return jobj; 
		} catch (JSONException e) {
			throw new IOException(e.toString());
		}
	}
	

}